const { sequelize, define, Op } = require('../db/db');
const fs = require('fs')


//获取models下的所有模型文件
function seachFile() {
    let arr = []
    fs.readdirSync(__dirname)
        .forEach(file => {

            if (file.endsWith('.js') && file !== 'index.js') {
                arr.push(file)
            }
        })
    return arr;
}

//注册模型实例
function registerModel(item) {
    let obj = { sequelize, Op }
    item.forEach(file => {
        let model = require(__dirname + '/' + file)
        let mn = file.substring(0, file.length - 3);
        let result = define(mn.toLowerCase(), model);
        obj[mn] = result;
    })
    return obj
}


let item = seachFile();

let obj = registerModel(item)

//建立关系
obj.User.belongsTo(obj.Rote,{foreignKey:'roteId'});
obj.Userquest.belongsTo(obj.User,{foreignKey:'userId'})
// obj.Userquest.belongsTo(obj.Quest,{foreignKey:'questId'})
obj.Quest.hasMany(obj.Userquest,{targetKey:'questId'})


obj.Quest.hasMany(obj.Scorelimit,{targetKey:'questId'})
obj.Quest.belongsTo(obj.Questtype,{foreignKey:'questTypeId'})
obj.Quest.belongsTo(obj.Queststate,{foreignKey:'questStateId'})
obj.Quest.hasMany(obj.Option,{targetKey:'questId'})


obj.Option.belongsTo(obj.Optiontype,{foreignKey:'optionTypeId'}),
// obj.Childoption.belongsTo(obj.Option,{foreignKey:'optionId'})
obj.Option.hasMany(obj.Childoption,{targetKey:'optionId'})
obj.Result.belongsTo(obj.Option,{foreignKey:'optionId'})

obj.Userquest.hasMany(obj.Result,{targetKey:'userquestId'})


//初始化表
obj.sync = async (forceObj = { force: false }) => {
    return await sequelize.sync(forceObj)
}


//初始化数据
obj.datainit = async () => {

    //初始化角色表
    if (await obj.Rote.count() === 0) {
        await obj.Rote.bulkCreate([
            { nkName: '管理员', describe: '后台管理员，拥有所以权限' },
            { nkName: '普通用户', describe: '没有权限' }
        ])
    }

    //初始化用户表
    let user = await obj.User.findOne({
        where: {
            user: 'admin'
        }
    })
    if (!user) {
        await obj.User.create({
            user: 'admin',
            pwd: '123456',
            roteId: 1
        })
    }

    //初始化问卷类型
    if(await obj.Questtype.count()===0){
        await obj.Questtype.bulkCreate([
            { typeName: '评分问卷'},
            { typeName: '普通问卷' }
        ])
    }

    //初始化问卷状态
    if(await obj.Queststate.count()===0){
        await obj.Queststate.bulkCreate([
            { stateName: '开启'},
            { stateName: '关闭' },
            { stateName: '待发布' }
        ])
    }

    //选项类表
    if(await obj.Optiontype.count()===0){
        await obj.Optiontype.bulkCreate([
            { typeName: '文本'},
            { typeName: '单选' },
            { typeName: '多选' },
            {typeName:'下拉框'}
        ])
    }

}



module.exports = obj;